

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/hexo_weini_blog/img/favicon.png">
  <link rel="icon" href="/hexo_weini_blog/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="weini wang">
  <meta name="keywords" content="">
  <meta name="description" content="1、排序1.1 冒泡排序 Bubble Sort             原理：冒泡排序大概的意思是依次比较相邻的两个数，然后根据大小做出排序，直至最后两位数。由于在排序过程中总是小数往前放，大数往后放，相当于气泡往上升，所以称作冒泡排序。代码实现如下：             12345678910111213141516171819202122function BubbleSort($arr)">
<meta property="og:type" content="website">
<meta property="og:title" content="php实现算法">
<meta property="og:url" content="https://weinirumo.gitee.io/hexo_weini_blog/php/algorithm.html">
<meta property="og:site_name" content="weini的播客">
<meta property="og:description" content="1、排序1.1 冒泡排序 Bubble Sort             原理：冒泡排序大概的意思是依次比较相邻的两个数，然后根据大小做出排序，直至最后两位数。由于在排序过程中总是小数往前放，大数往后放，相当于气泡往上升，所以称作冒泡排序。代码实现如下：             12345678910111213141516171819202122function BubbleSort($arr)">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://weinirumo.gitee.io/hexo_weini_blog/img/merge_sort_001.png">
<meta property="og:image" content="https://weinirumo.gitee.io/hexo_weini_blog/img/merge_sort_002.png">
<meta property="og:image" content="https://weinirumo.gitee.io/hexo_weini_blog/img/merge_sort_003.png">
<meta property="article:published_time" content="2021-10-12T09:16:11.000Z">
<meta property="article:modified_time" content="2021-10-13T01:56:34.957Z">
<meta property="article:author" content="weini wang">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://weinirumo.gitee.io/hexo_weini_blog/img/merge_sort_001.png">
  
  <title>php实现算法 - weini的播客</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/hexo_weini_blog/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/monokai.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/hexo_weini_blog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"weinirumo.gitee.io","root":"/hexo_weini_blog/","version":"1.8.12","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/hexo_weini_blog/local-search.xml"};
  </script>
  <script  src="/hexo_weini_blog/js/utils.js" ></script>
  <script  src="/hexo_weini_blog/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 60vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/hexo_weini_blog/">
      <strong>weini的blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hexo_weini_blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" target="_self" href="javascript:;" role="button"
                 data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-list"></i>
                技术积累
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" href="/hexo_weini_blog/2021/09/27/go%E8%AF%AD%E8%A8%80/">
                    
                    Go语言
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" href="/hexo_weini_blog/2021/10/12/php/">
                    
                    PHP
                  </a>
                
              </div>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hexo_weini_blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hexo_weini_blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hexo_weini_blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hexo_weini_blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/hexo_weini_blog/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="php实现算法">
              
            </span>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      <div class="container nopadding-x-md">
        <div class="py-5" id="board"
          >
          
          <div class="container">
            <div class="row">
              <div class="col-12 col-md-10 m-auto">
                

<article class="page-content">
  <h1 id="1、排序"><a href="#1、排序" class="headerlink" title="1、排序"></a>1、排序</h1><h2 id="1-1-冒泡排序-Bubble-Sort"><a href="#1-1-冒泡排序-Bubble-Sort" class="headerlink" title="1.1 冒泡排序 Bubble Sort"></a>1.1 冒泡排序 Bubble Sort</h2><div class="note note-success">
            <p>原理：冒泡排序大概的意思是依次比较相邻的两个数，然后根据大小做出排序，直至最后两位数。由于在排序过程中总是小数往前放，大数往后放，相当于气泡往上升，所以称作冒泡排序。代码实现如下：</p>
          </div>

<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs php"><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BubbleSort</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span></span>) </span>&#123;<br>    <span class="hljs-comment">// 判断参数是否是数组</span><br>    <span class="hljs-keyword">if</span> (!is_array(<span class="hljs-variable">$arr</span>) || <span class="hljs-keyword">empty</span>(<span class="hljs-variable">$arr</span>)) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>    &#125;<br>    <span class="hljs-comment">// 确定要冒泡的轮数</span><br>    <span class="hljs-variable">$len</span> = count(<span class="hljs-variable">$arr</span>);<br>    <span class="hljs-keyword">for</span> (<span class="hljs-variable">$i</span> = <span class="hljs-number">0</span>; <span class="hljs-variable">$i</span> &lt; <span class="hljs-variable">$len</span> - <span class="hljs-number">1</span>; <span class="hljs-variable">$i</span>++) &#123;<br>        <span class="hljs-comment">// 每轮比较，都要去掉之前确定好顺序的数。第一轮去掉0个，第二轮去掉1个。。。</span><br>        <span class="hljs-keyword">for</span>(<span class="hljs-variable">$j</span>= <span class="hljs-number">0</span>; <span class="hljs-variable">$j</span> &lt; <span class="hljs-variable">$len</span> - <span class="hljs-variable">$i</span> - <span class="hljs-number">1</span>; <span class="hljs-variable">$j</span>++) &#123;<br>            <span class="hljs-comment">// 两数相比，如果$arr[$j] 大于 $arr[$j+1] -- 交换位置，往后移动</span><br>            <span class="hljs-keyword">if</span> (<span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>] &gt; <span class="hljs-variable">$arr</span>[j+<span class="hljs-number">1</span>]) &#123;<br>                <span class="hljs-variable">$temp</span> = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span> + <span class="hljs-number">1</span>];<br>                <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span> + <span class="hljs-number">1</span>] = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>];<br>                <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>] = <span class="hljs-variable">$temp</span>;<br>            &#125;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h2 id="1-2-选择排序-Selection-sort"><a href="#1-2-选择排序-Selection-sort" class="headerlink" title="1.2 选择排序 Selection sort"></a>1.2 选择排序 Selection sort</h2><div class="note note-success">
            <p>原理：首先在未排序序列中找到最小元素，存放到排序序列的起始位置，然后，再从剩余未排序元素中继续寻找最小元素，然后放到排序序列末尾。以此类推，直到所有元素均排序完毕。<br>示例代码如下：</p>
          </div>

<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">selectSort</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span></span>) </span>&#123;<br>    <span class="hljs-keyword">if</span>(!is_array(<span class="hljs-variable">$arr</span>) || <span class="hljs-keyword">empty</span>(<span class="hljs-variable">$arr</span>)) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>    &#125;<br><br>    <span class="hljs-variable">$len</span> = count(<span class="hljs-variable">$arr</span>);<br>    <span class="hljs-comment">// $i 当前最小值的位置，需要参与比较的元素</span><br>    <span class="hljs-keyword">for</span> (<span class="hljs-variable">$i</span>=<span class="hljs-number">0</span>; <span class="hljs-variable">$i</span> &lt; <span class="hljs-variable">$len</span> - <span class="hljs-number">1</span>; <span class="hljs-variable">$i</span>++) &#123; <br>        <span class="hljs-comment">// 先假设最小的值的位置</span><br>        <span class="hljs-variable">$p</span> = <span class="hljs-variable">$i</span>;<br><br>        <span class="hljs-keyword">for</span> (<span class="hljs-variable">$j</span>=<span class="hljs-variable">$i</span> + <span class="hljs-number">1</span>; <span class="hljs-variable">$j</span> &lt; <span class="hljs-variable">$len</span>; <span class="hljs-variable">$j</span>++) &#123; <br>            <span class="hljs-comment">// $arr[$p]是当前已知的最小值</span><br>            <span class="hljs-comment">// 比较，发现更小的，记录下最小值的位置；并且在下次比较时，应该采用已知的最小值进行比较。</span><br>            <span class="hljs-variable">$p</span> = (<span class="hljs-variable">$arr</span>[<span class="hljs-variable">$p</span>] &lt;= <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>]) ? <span class="hljs-variable">$p</span>:<span class="hljs-variable">$j</span>;<br>        &#125;<br><br>        <span class="hljs-comment">// 已经确定了最小值，保存到$p中</span><br>        <span class="hljs-comment">// 如果发现 最小值的位置和当前假设的位置$i不同，则互换位置</span><br>        <span class="hljs-keyword">if</span> (<span class="hljs-variable">$p</span> != <span class="hljs-variable">$i</span>) &#123;<br>            <span class="hljs-variable">$tmp</span> = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$p</span>];<br>            <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$p</span>] = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$i</span>];<br>            <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$i</span>] = <span class="hljs-variable">$tmp</span>;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h2 id="1-3-插入排序-Insert-Sort"><a href="#1-3-插入排序-Insert-Sort" class="headerlink" title="1.3 插入排序 Insert Sort"></a>1.3 插入排序 Insert Sort</h2><div class="note note-success">
            <p>原理：<br>    通过构建有序序列，对于未排序数据，在已排序序列中从后向前扫描，找到相应位置并插入。插入排序在实现上，通常采用in-place排序（即只需用到O(1)的额外空间的排序），因而在从后向前扫描过程中，需要反复把已排序元素逐步向后挪位，为最新元素提供插入空间。<br>步骤：<br>    1 从第一个元素开始，该元素可以认为已经被排序<br>    2 取出下一个元素，在已经排序的元素序列中从后向前扫描<br>    3 如果该元素（已排序）大于新元素，将该元素移到下一位置<br>    4 重复步骤3，直到找到已排序的元素小于或者等于新元素的位置<br>    5 将新元素插入到该位置中<br>    6 重复步骤2<br>示例代码如下：</p>
          </div>

<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs php"><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">insertSort</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span></span>) </span>&#123;<br>    <span class="hljs-keyword">if</span>(!is_array(<span class="hljs-variable">$arr</span>) || <span class="hljs-keyword">empty</span>(<span class="hljs-variable">$arr</span>)) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>    &#125;<br><br>    <span class="hljs-variable">$len</span> = count(<span class="hljs-variable">$arr</span>);<br>    <span class="hljs-comment">// 从1开始，第一个元素不需要比较</span><br>    <span class="hljs-keyword">for</span> (<span class="hljs-variable">$i</span> = <span class="hljs-number">1</span>; <span class="hljs-variable">$i</span> &lt; <span class="hljs-variable">$len</span>; <span class="hljs-variable">$i</span>++) &#123;<br>        <span class="hljs-comment">// 获得当前需要比较的元素值</span><br>        <span class="hljs-variable">$tmp</span> = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$i</span>];<br>        <span class="hljs-comment">// 内层循环，比较并插入</span><br>        <span class="hljs-comment">// 从$i的前一位开始往前比较</span><br>        <span class="hljs-keyword">for</span> (<span class="hljs-variable">$j</span> = <span class="hljs-variable">$i</span> - <span class="hljs-number">1</span>; <span class="hljs-variable">$j</span> &gt;= <span class="hljs-number">0</span>; <span class="hljs-variable">$j</span>--) &#123;<br>            <span class="hljs-comment">// $arr[$i] 需要插入的元素</span><br>            <span class="hljs-comment">// $arr[$j] 需要比较的元素</span><br>            <span class="hljs-keyword">if</span> (<span class="hljs-variable">$tmp</span> &lt; <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>]) &#123;<br>                <span class="hljs-comment">// 发现插入的元素要小，交换位置</span><br>                <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span> + <span class="hljs-number">1</span>] = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>];<br>                <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>] = <span class="hljs-variable">$tmp</span>;<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-keyword">break</span>;<br>            &#125;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h2 id="1-4-归并排序"><a href="#1-4-归并排序" class="headerlink" title="1.4 归并排序"></a>1.4 归并排序</h2><div class="note note-success">
            <p>原理：<br>    利用递归，先拆分、后合并、再排序。<br>步骤：<br>    1 均分数列为两个子数列<br>    2 递归重复上一步骤，直到子数列只有一个元素<br>    3 父数列合并两个子数列并排序，递归返回数列<br>示例代码如下：</p>
          </div>

<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mergeSort</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span></span>) </span>&#123;<br>    <span class="hljs-keyword">if</span>(!is_array(<span class="hljs-variable">$arr</span>) || <span class="hljs-keyword">empty</span>(<span class="hljs-variable">$arr</span>)) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>    &#125;<br><br>    <span class="hljs-variable">$len</span> = count(<span class="hljs-variable">$arr</span>);<br><br>    <span class="hljs-comment">// 递归结束条件</span><br>    <span class="hljs-keyword">if</span> (<span class="hljs-variable">$len</span> &lt;= <span class="hljs-number">1</span>) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>    &#125;<br>    <span class="hljs-variable">$mid</span> = intval(<span class="hljs-variable">$len</span> / <span class="hljs-number">2</span>); <span class="hljs-comment">// 取数组中间</span><br>    <span class="hljs-variable">$left</span> = array_slice(<span class="hljs-variable">$arr</span>, <span class="hljs-number">0</span>, <span class="hljs-variable">$mid</span>); <span class="hljs-comment">// 拆分数组0-mid这部分给左边</span><br>    <span class="hljs-variable">$right</span> = array_slice(<span class="hljs-variable">$arr</span>, <span class="hljs-variable">$mid</span>); <span class="hljs-comment">// 拆分数组mid-末尾给右边</span><br>    <br>    <span class="hljs-variable">$left</span> = mergeSort(<span class="hljs-variable">$left</span>); <span class="hljs-comment">// 左边拆分完后开始递归合并往上走</span><br>    <span class="hljs-variable">$right</span> = mergeSort(<span class="hljs-variable">$right</span>); <span class="hljs-comment">// 右边拆分完毕后开始递归往上走</span><br><br>    <span class="hljs-keyword">return</span> merge(<span class="hljs-variable">$left</span>, <span class="hljs-variable">$right</span>); <span class="hljs-comment">// 合并两个数组，继续递归</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">merge</span>(<span class="hljs-params"><span class="hljs-variable">$arrA</span>, <span class="hljs-variable">$arrB</span></span>) </span>&#123;<br>    <span class="hljs-variable">$arrC</span> = []; <br>    <span class="hljs-keyword">while</span>(count(<span class="hljs-variable">$arrA</span>) &amp;&amp; count(<span class="hljs-variable">$arrB</span>)) &#123;<br>        <span class="hljs-variable">$arrC</span>[] = <span class="hljs-variable">$arrA</span>[<span class="hljs-number">0</span>] &lt; <span class="hljs-variable">$arrB</span>[<span class="hljs-number">0</span>] ? array_shift(<span class="hljs-variable">$arrA</span>) : array_shift(<span class="hljs-variable">$arrB</span>);<br>    &#125;<br><br>    <span class="hljs-keyword">return</span> array_merge(<span class="hljs-variable">$arrC</span>, <span class="hljs-variable">$arrA</span>, <span class="hljs-variable">$arrB</span>);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>图示:<br><img src="/hexo_weini_blog/img/merge_sort_001.png" srcset="/hexo_weini_blog/img/loading.gif" lazyload><br><img src="/hexo_weini_blog/img/merge_sort_002.png" srcset="/hexo_weini_blog/img/loading.gif" lazyload><br><img src="/hexo_weini_blog/img/merge_sort_003.png" srcset="/hexo_weini_blog/img/loading.gif" lazyload></p>
<div class="note note-warning">
            <p>图片来源：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/chengxiao/p/6194356.html">图解排序算法(四)之归并排序</a></p>
          </div>

<h2 id="1-5-快速排序-Quick-Sort"><a href="#1-5-快速排序-Quick-Sort" class="headerlink" title="1.5 快速排序 Quick Sort"></a>1.5 快速排序 Quick Sort</h2><div class="note note-success">
            <p>快速排序是由东尼·霍尔所发展的一种排序算法。<br>原理：<br>    在平均状况下，排序 n 个项目要Ο(n log n)次比较。在最坏状况下则需要Ο(n2)次比较，但这种状况并不常见。事实上，快速排序通常明显比其他Ο(n log n) 算法更快，因为它的内部循环（inner loop）可以在大部分的架构上很有效率地被实现出来，且在大部分真实世界的数据，可以决定设计的选择，减少所需时间的二次方项之可能性。<br>步骤：<br>    1 从数列中挑出一个元素，称为 “基准”（pivot）<br>    2 重新排序数列，所有元素比基准值小的摆放在基准前面，所有元素比基准值大的摆在基准的后面（相同的数可以到任一边）。在这个分区退出之后，该基准就处于数列的中间位置。这个称为分区（partition）操作<br>    3 递归地（recursive）把小于基准值元素的子数列和大于基准值元素的子数列排序。<br>示例代码如下：</p>
          </div>

<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">quickSort</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span></span>) </span>&#123;<br>    <span class="hljs-keyword">if</span> (!is_array(<span class="hljs-variable">$arr</span>)) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>    &#125;<br><br>    <span class="hljs-variable">$len</span> = count(<span class="hljs-variable">$arr</span>);<br><br>    <span class="hljs-keyword">if</span> (<span class="hljs-variable">$len</span> &lt;= <span class="hljs-number">1</span>) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>    &#125;<br><br>    <span class="hljs-variable">$left</span> = [];<br>    <span class="hljs-variable">$right</span> = [];<br><br>    <span class="hljs-keyword">for</span> (<span class="hljs-variable">$i</span> = <span class="hljs-number">1</span>; <span class="hljs-variable">$i</span> &lt; <span class="hljs-variable">$len</span>; <span class="hljs-variable">$i</span>++) &#123;<br>        <span class="hljs-keyword">if</span> (<span class="hljs-variable">$arr</span>[<span class="hljs-variable">$i</span>] &lt; <span class="hljs-variable">$arr</span>[<span class="hljs-number">0</span>]) &#123;<br>            <span class="hljs-variable">$left</span>[] = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$i</span>];<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-variable">$right</span>[] = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$i</span>];<br>        &#125;<br>    &#125;<br>    <span class="hljs-variable">$left</span> = quickSort(<span class="hljs-variable">$left</span>);<br>    <span class="hljs-variable">$right</span> = quickSort(<span class="hljs-variable">$right</span>);<br>    <span class="hljs-keyword">return</span> array_merge(<span class="hljs-variable">$left</span>, [<span class="hljs-variable">$arr</span>[<span class="hljs-number">0</span>]], <span class="hljs-variable">$right</span>);<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="1-6-希尔排序-Shell-Sort"><a href="#1-6-希尔排序-Shell-Sort" class="headerlink" title="1.6 希尔排序 Shell Sort"></a>1.6 希尔排序 Shell Sort</h2><div class="note note-success">
            <p>希尔排序属于插入类排序，是将整个有序序列分割成若干个小的子序列分别进行插入排序。<br>排序过程：先取一个正整数d1&lt;n，把所有序号相隔d1的数组元素放一组，组内进行直接插入排序，然后取d2&lt;d1，重复上述分组和排序操作，直至d1=1，即所有记录放进一个组中排序为止。（将每间隔一定步距的数取出来进行比较，比如gap=5，就是把第1个、第6个、第11个…数取出来进行插入排序）<br>优点：<br>    当n值很大时，数据项每一趟排序需要移动的个数很少，但数据项的距离很长；当n值减小时，每一趟需要移动的数据增多，此时已经接近于它们排序后的最终位置。<br>示例代码如下：</p>
          </div>

<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs php"><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">shellSort</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span></span>)</span><br><span class="hljs-function"></span>&#123;<br>    <span class="hljs-variable">$count</span> = count(<span class="hljs-variable">$arr</span>);<br>    <span class="hljs-variable">$inc</span> = <span class="hljs-variable">$count</span>;<br>    <span class="hljs-keyword">do</span> &#123;<br>        <span class="hljs-variable">$inc</span> = ceil(<span class="hljs-variable">$inc</span> / <span class="hljs-number">2</span>);<br>        <span class="hljs-keyword">for</span> (<span class="hljs-variable">$i</span> = <span class="hljs-variable">$inc</span>; <span class="hljs-variable">$i</span> &lt; <span class="hljs-variable">$count</span>; <span class="hljs-variable">$i</span>++) &#123;<br>            <span class="hljs-variable">$temp</span> = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$i</span>]; <span class="hljs-comment">// 设置哨兵</span><br>            <span class="hljs-comment">// 需将$temp插入有序增量子表</span><br>            <span class="hljs-keyword">for</span> (<span class="hljs-variable">$j</span> = <span class="hljs-variable">$i</span> - <span class="hljs-variable">$inc</span>; <span class="hljs-variable">$j</span> &gt;= <span class="hljs-number">0</span> &amp;&amp; <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span> + <span class="hljs-variable">$inc</span>] &lt; <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>]; <span class="hljs-variable">$j</span> -= <span class="hljs-variable">$inc</span>) &#123;<br>                <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span> + <span class="hljs-variable">$inc</span>] = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span>]; <span class="hljs-comment">// 记录后移</span><br>            &#125;<br>            <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$j</span> + <span class="hljs-variable">$inc</span>] = <span class="hljs-variable">$temp</span>;<br>        &#125;<br>    &#125; <span class="hljs-keyword">while</span> (<span class="hljs-variable">$inc</span> &gt; <span class="hljs-number">1</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable">$arr</span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h1 id="2-搜索"><a href="#2-搜索" class="headerlink" title="2 搜索"></a>2 搜索</h1><h2 id="2-1-二分查找-Binary-Search"><a href="#2-1-二分查找-Binary-Search" class="headerlink" title="2.1 二分查找 Binary Search"></a>2.1 二分查找 Binary Search</h2><div class="note note-success">
            <p>原理：<br>    首先，将表中间位置记录的值与查找值比较，如果两者相等，则查找成功；否则利用中间位置将表分成前、后两个子表，如果中间位置的值大于查找值，则进一步查找前一子表，否则进一步查找后一子表。<br>重复以上过程，直到找到满足条件的记录，使查找成功，或直到子表不存在为止，此时查找不成功。<br>步骤：</p><ol><li>将数组的第一个位置设置为下边界(0)。</li><li>将数组最后一个元素所在的位置设置为上边界(数组的长度减 1)。</li><li>若下边界等于或小于上边界，则做如下操作：<br> a. 将中点设置为floor((上边界+下边界)/2)。<br> b. 如果中点的元素小于查询的值，则将下边界设置为中点元素所在下标加1。<br> c. 如果中点的元素大于查询的值，则将上边界设置为中点元素所在下标减1。<br> d. 否则中点元素即为要查找的数据，可以进行返回。</li></ol><p>示例代码如下：</p>
          </div>


<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs php"><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">binarySearch</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span>, <span class="hljs-variable">$res</span></span>) </span>&#123;<br>    <span class="hljs-variable">$right</span> = count(<span class="hljs-variable">$arr</span>);<br>    <span class="hljs-variable">$left</span> = <span class="hljs-number">0</span>;<br><br>    <span class="hljs-keyword">while</span>(<span class="hljs-variable">$left</span> &lt;= <span class="hljs-variable">$right</span>) &#123;<br>        <span class="hljs-variable">$middle</span> = floor((<span class="hljs-variable">$right</span> + <span class="hljs-variable">$left</span>) / <span class="hljs-number">2</span>);<br><br>        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">isset</span>(<span class="hljs-variable">$arr</span>[<span class="hljs-variable">$middle</span>])) &#123;<br>            <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;<br>        &#125;<br><br>        <span class="hljs-keyword">if</span> (<span class="hljs-variable">$arr</span>[<span class="hljs-variable">$middle</span>] == <span class="hljs-variable">$res</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-variable">$middle</span>;<br>        &#125;<br><br>        <span class="hljs-keyword">if</span> (<span class="hljs-variable">$arr</span>[<span class="hljs-variable">$middle</span>] &lt; <span class="hljs-variable">$res</span>) &#123;<br>            <span class="hljs-variable">$left</span> = <span class="hljs-variable">$middle</span> + <span class="hljs-number">1</span>;<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-variable">$right</span> = <span class="hljs-variable">$middle</span> - <span class="hljs-number">1</span>;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;<br>&#125;<br><br><span class="hljs-comment">// 第二种实现</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">binarySearch2</span>(<span class="hljs-params"><span class="hljs-variable">$arr</span>, <span class="hljs-variable">$search</span></span>) </span>&#123;<br>    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">empty</span>(<span class="hljs-variable">$arr</span>)) &#123;<br>        <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;<br>    &#125;<br><br>    <span class="hljs-variable">$low</span> = <span class="hljs-number">0</span>;<br>    <span class="hljs-variable">$high</span> = count(<span class="hljs-variable">$arr</span>) - <span class="hljs-number">1</span>;<br><br>    <span class="hljs-keyword">while</span> (<span class="hljs-variable">$low</span> &lt;= <span class="hljs-variable">$high</span>) &#123;<br>        <span class="hljs-comment">// 这样的写法没有溢出的风险</span><br>        <span class="hljs-variable">$mid</span> = intval((<span class="hljs-variable">$high</span> - <span class="hljs-variable">$low</span>) / <span class="hljs-number">2</span>) + <span class="hljs-variable">$low</span>;<br>        <span class="hljs-variable">$val</span> = <span class="hljs-variable">$arr</span>[<span class="hljs-variable">$mid</span>];<br><br>        <span class="hljs-keyword">if</span> (<span class="hljs-variable">$search</span> == <span class="hljs-variable">$val</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-variable">$mid</span>;<br>        &#125; <span class="hljs-keyword">elseif</span> (<span class="hljs-variable">$search</span> &lt; <span class="hljs-variable">$val</span>) &#123;<br>            <span class="hljs-variable">$high</span> = <span class="hljs-variable">$mid</span> - <span class="hljs-number">1</span>;<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-variable">$low</span> = <span class="hljs-variable">$mid</span> + <span class="hljs-number">1</span>;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

  
</article>

              </div>
            </div>
          </div>
        </div>
      </div>
    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/hexo_weini_blog/js/events.js" ></script>
<script  src="/hexo_weini_blog/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/hexo_weini_blog/js/local-search.js" ></script>



  
    <script  src="/hexo_weini_blog/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/hexo_weini_blog/js/boot.js" ></script>


</body>
</html>
